package Interact;
// 使用信号灯法解决生产消费者问题
public class TestPcFlag {
    public static void main(String[] args) {
        Video video = new Video();
        new Actor(video).start();
        new Watcher(video).start();
    }
}
// 生产者--演员，消费者--观众，产品--视频
class Actor extends Thread {
    Video video=new Video();
    public Actor(Video video){
        this.video=video;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if(i%2==0){
                this.video.play("快乐再出发 播放中。");
            }else{
                this.video.play("抖音：打造美好生活。");
            }
        }
    }
}
class Watcher extends Thread {
    Video video=new Video();
    public Watcher(Video video){
        this.video=video;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            this.video.watch();
        }
    }
}

class Video{
    // 演员表演，观众等待 T
    // 观众观看，演员等待 F
    private String voice;  // 要表演的节目
    private boolean flag=true;

    // 表演
    public synchronized void play(String voice){
        // whether to play
        if(!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        // play
        System.out.println("演员表演了 "+voice);
        // 通知观众观看
        this.notifyAll();
        this.voice=voice;
        this.flag=!flag;
    }

    // 观看
    public synchronized void watch(){
        if(flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("观众刚看了："+voice);
        this.notifyAll();
        this.flag=!flag;
    }
}